package hehe.router.easy.rule;

import hehe.router.Controller;
import hehe.router.RequestUrl;
import hehe.router.util.RouteHelper;
import java.util.*;

/**
 * pathinfo 路由规则
 *<B>说明：</B>
 *<pre>
 * 直接通过解析pathinfo地址,pathinfo 的基本格式:/控制器名称/控制器方法名称
 * 比如:index/index 对应:控制器路径app.controller.IndexController,控制器方法名称：indexAction
 *
 * 示例:普通路由
 *
 *
 *
 *</pre>
 *<B>示例：</B>
 *<pre>
 *  略
 *</pre>
 *<B>日志：</B>
 *<pre>
 *  略
 *</pre>
 *<B>注意事项：</B>
 *<pre>
 *  略
 *</pre>
 */
public class PathinfoRule extends Rule
{
    /**
     * pathinfo 分隔符
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    private static final String PATH_INFO_SPLIT = "/";

    public PathinfoRule()
    {

    }

    public PathinfoRule(Map<String,Object> attrs)
    {
        super(attrs);
    }

    /**
     * 构建pathinfo其余参数
     *<B>说明：</B>
     *<pre>
     * 比如:index/index/name/admin/age/2
     *</pre>
     */
    protected Map<String,String>  buildParams(List<String> paths)
    {
        if (paths == null || paths.size() == 0) {
            return new HashMap<String,String>();
        }

        Map<String,String> params = new HashMap<>();

        for (int i = 0;i < paths.size();i = i+2) {
            params.put(paths.get(i),paths.get(i+1));
        }

        return params;
    }

    @Override
    public Controller parseRequest(String pathinfo)
    {
        if (pathinfo == null) {
            return null;
        }

        String[] pathinfos = pathinfo.substring(1, pathinfo.length()).split(PATH_INFO_SPLIT);
        List<String> paths =  RouteHelper.arrayToLinkedList(pathinfos);

        String controllerName = "",
                controllerAction = "";

        // 读取控制器名
        if (paths.size() > 0 && paths.get(0) != null) {
            controllerName = paths.get(0);
            paths.remove(0);
        }

        // 读取控制器方法
        if (paths.size() > 0 && paths.get(0) != null) {
            controllerAction = paths.get(0);
            paths.remove(0);
        }

        // 分析参数
        Map<String,String> params = this.buildParams(paths);
        // 创建实例对象
        return new Controller(controllerName,controllerAction,params);
    }

    @Override
    public RequestUrl parseUrL(String url, Map<String, String> params) {
        return null;
    }
}
